package cn.wizzer.app.web.modules.controllers.platform.bus.bggl;

import cn.wizzer.app.bus.modules.models.*;
import cn.wizzer.app.bus.modules.services.*;
import cn.wizzer.app.sys.modules.models.Sys_user;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysUnitService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.base.Globals;
import cn.wizzer.app.web.commons.doc.DocUtils;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.DateUtil;
import cn.wizzer.app.web.commons.utils.ShiroUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.app.web.modules.controllers.open.file.UploadController;
import cn.wizzer.framework.base.Result;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Times;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.Param;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.text.ParseException;
import java.util.*;
import java.util.stream.Collectors;

import org.nutz.trans.Atom;
import org.nutz.trans.Trans;



/**
 * 报告编制  虞秀斌  2019-11
 */
@IocBean
@At("/platform/bus/bggl")
public class OrganizationController {
    private static final Log log = Logs.get();
    @Inject
    private YJbxxService yjbxxService;
    @Inject
    private YJbxxLcxxService yjbxxlcxxservice;
    @Inject
    private SysUnitService sysUnitService;
    @Inject
    private SysDictService sysDictService;
    @Inject
    private SysUserService sysUserService;
    @Inject
    private ShiroUtil shiroUtil;
    @Inject
    private BusinessFileInfoService businessFileInfoService;
    @Inject
    private YJbxxJyxmService yjbxxjyxmservice;
    @Inject
    private InspectionItemJudgeService inspectionItemJudgeService;

    @At("/organization/?")
    @Ok("beetl:/platform/bus/bggl/organization.html")
    @RequiresPermissions("bus.bggl.tobz")
    public void edit(String id,HttpServletRequest req) throws ParseException {
        YJbxx obj = yjbxxService.fetchLinks(yjbxxService.fetch(id),"yjbxxjyxm");;
        if(StringUtils.isNotBlank(obj.getJywcrq())&&StringUtils.isBlank(obj.getJyrq())) {
            obj.setJyrq(DateUtil.getDate(obj.getOpAt(), "yyyy/MM/dd") + "-" + DateUtil.StringFormat(obj.getJywcrq(), "yyyy/MM/dd"));
        }
        /*for(YJbxxJyxm item : obj.getYjbxxjyxm()){
                item.setItemJudges(inspectionItemJudgeService.query(Cnd.NEW().where("itemId","=",item.getInsItemId())));
        }*/
        req.setAttribute("obj",JSONObject.fromObject(obj));
        req.setAttribute("yplxOptions", JSONArray.fromObject(sysDictService.dictCodeTree("yplx")));
        req.setAttribute("zhOptions", JSONArray.fromObject(sysDictService.dictTree("zh")));
        List<NutMap> list = sysDictService.dictTreeChild("xzqh");
        if(StringUtils.isNotBlank(obj.getSzcs())){
            list = sysDictService.dictTreeChilds(obj.getSzcs().split(","),list);
        }

        req.setAttribute("szcsOptions", JSONArray.fromObject(list));
        req.setAttribute("ypczOptions", JSONArray.fromObject(sysDictService.dictTree("ypcz")));
        req.setAttribute("jylxOptions", JSONArray.fromObject(sysDictService.dictCodeTree("jylx")));
        req.setAttribute("unitOptions", JSONArray.fromObject(sysUnitService.getJybmTree()));
        req.setAttribute("userOptions", JSONArray.fromObject(sysUserService.getUserAudit("1")));
        req.setAttribute("userId",shiroUtil.getPrincipalProperty("id").toString());
        req.setAttribute("username",shiroUtil.getPrincipalProperty("username").toString());
        req.setAttribute("yplxMap", JSONObject.fromObject(sysDictService.getCodeMap("yplx")));
        req.setAttribute("judgConditionMap", JSONObject.fromObject(sysDictService.getCodeMap("judgCondition")));
        req.setAttribute("inspectorJudgeOptions", JSONArray.fromObject(sysDictService.dictCodeTree("inspectorJudge")));



        //认证章，算了从页面获取吧

    }

    @At
    @Ok("json")
    @RequiresPermissions("bus.bggl.tobz")
    @SLog(tag = "编制修改样品", msg = "样品:${args[0].ypbh}")
    public Object doAdd(@Param("..") YJbxx obj,@Param("..") YJbxxLcxx lcxx) {
        try {
            if(StringUtils.isNotEmpty(obj.getJylx())&&!obj.getJylx().equals("jdcc")&&!obj.getJylx().equals("jbts")&&!obj.getJylx().equals("zxzz")){
                obj.setCydw("");
                obj.setCydwId("");
                obj.setCyryBy("");
                obj.setCyjs("");
                obj.setCyrq("");
                obj.setCydbh("");
                obj.setCydd("");
            }
            lcxx.setOpBy(StringUtil.getPlatformUid());
            lcxx.setOpAt(Times.getTS());
            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    lcxx.setId(null);
                    yjbxxlcxxservice.execute(Sqls.create("update y_jbxx_lcxx set delflag=1 where lczt>="+obj.getLczt()+" and jbxxid='"+obj.getId()+"'"));
                    yjbxxlcxxservice.insert(lcxx);
                    obj.setLczt(obj.getLczt());
                    yjbxxService.update(obj);
                    yjbxxjyxmservice.execute(Sqls.create("delete from y_jbxx_jyxm  where jbxxid='"+obj.getId()+"'"));
                    for(YJbxxJyxm jyxm : obj.getYjbxxjyxm()){
                        jyxm.setJbxxId(obj.getId());
                        yjbxxjyxmservice.insert(jyxm);
                    }
                }
            });
            return Result.success("操作成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("system.error");
        }
    }

    @At
    @Ok("json")
    @RequiresPermissions("bus.bggl.tobz")
    @SLog(tag = "编制保存报告信息", msg = "样品:${args[0].ypbh}")
    public Object editDo(@Param("..") YJbxx obj,@Param("..") YJbxxLcxx lcxx) {
        try {
            if(StringUtils.isNotEmpty(obj.getJylx())&&!obj.getJylx().equals("jdcc")&&!obj.getJylx().equals("jbts")&&!obj.getJylx().equals("zxzz")){
                obj.setCydw("");
                obj.setCydwId("");
                obj.setCyryBy("");
                obj.setCyrq("");
                obj.setCydbh("");
                obj.setCyjs("");
                obj.setCydd("");
            }
            lcxx.setOpBy(StringUtil.getPlatformUid());
            lcxx.setOpAt(Times.getTS());
            //验证编号是否重复，若重复则不允许提交，并且重新生成
            int count = yjbxxService.count(Sqls.create("select count(1) from y_jbxx where bgbh = '" + obj.getBgbh()+"' and id !='"+obj.getId()+"' and delflag=0"));
            if(count>0) {//存在重复
                return Result.error(99,"报告编号"+obj.getBgbh()+"重复");
            }
            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    lcxx.setId(null);
                    yjbxxlcxxservice.execute(Sqls.create("update y_jbxx_lcxx set delflag=1 where lczt>="+obj.getLczt()+" and jbxxid='"+obj.getId()+"'"));
                    yjbxxlcxxservice.insert(lcxx);
                    obj.setLczt(obj.getLczt());
                    yjbxxService.update(obj);
                    yjbxxjyxmservice.execute(Sqls.create("delete from y_jbxx_jyxm  where jbxxid='"+obj.getId()+"'"));
                    for(YJbxxJyxm jyxm : obj.getYjbxxjyxm()){
                        jyxm.setJbxxId(obj.getId());
                        yjbxxjyxmservice.insert(jyxm);
                    }
                }
            });
            return Result.success("操作成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("system.error");
        }
    }

    @Aop(TransAop.READ_COMMITTED)
    @At("/createAttached/?")
    @Ok("json")
    @RequiresPermissions("bus.bggl")
    @SLog(tag = "附页编辑", msg = "样品:${args[0]}")
    public Object createAttached(String fileName) {
        try {
            String fileNameDocx = fileName + ".docx";
            String date = DateUtil.format(new Date(), "yyyy") + "/" + DateUtil.format(new Date(), "MM") + "/" + DateUtil.format(new Date(), "dd");
            String filePath = "/report/" + date + "/" + fileNameDocx;
            String uploadPath = this.getUploadPathConfig();
            BusinessFileInfo report = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("fileName", "=", fileName));
            if (report != null) {
                return Result.success("附页已经存在！不需要生成啦").addData(report.getFilePath());
            }
            File file = new File(uploadPath + filePath);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            if(!file.exists()){
                //编制附页的时候如果没有附页文件则创建
                //先获取样品信息
                String id = fileName.replace("fy","");
                YJbxx obj = yjbxxService.fetchLinks(yjbxxService.fetch(id),"yjbxxjyxm");
                obj.setLczt("4");
                YJbxxLcxx lcxx = yjbxxlcxxservice.fetch(Cnd.NEW().and("jbxxId", "=", obj.getId()).and("delFlag","=","0").and("lczt", "=", "2"));
                lcxx.setJbxxId(obj.getId());
                lcxx.setJyry("");
                lcxx.setLczt(obj.getLczt());
                lcxx.setSpyj("编制中，创建附页");
                lcxx.setOpBy(StringUtil.getPlatformUid());
                lcxx.setOpAt(Times.getTS());
                yjbxxlcxxservice.execute(Sqls.create("update y_jbxx_lcxx set delflag=1 where lczt>="+obj.getLczt()+" and jbxxid='"+obj.getId()+"'"));
                yjbxxlcxxservice.insert(lcxx);
                yjbxxService.update(obj);
               /* Map<String, String> map = new HashMap<String, String>();
                map.put("P3_bgbh", obj.getBgbh());*/
                BusinessFileInfo businessFileInfo = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("infoName", "=", "附页").and("productType","like","%"+obj.getYplx()+"%").and("disabled", "=", false));
                if (businessFileInfo != null) {
                    String reportTemplateFile = businessFileInfo.getFilePath();
                    Map judgConditionMap =sysDictService.getCodeMap("judgCondition");
                    Map inspectorJudgeMap = sysDictService.getCodeMap("inspectorJudge");
                    for(YJbxxJyxm item : obj.getYjbxxjyxm()){
                        item.setInspectorJudge(StringUtil.getDict(item.getInspectorJudge(),inspectorJudgeMap));
                        item.setItemJudges(inspectionItemJudgeService.query(Cnd.NEW().where("itemId","=",item.getInsItemId())));
                    }
                    //List<String> count = obj.getYjbxxjyxm().stream().filter(s -> s.getInspectionItemOrder()!=null&&s.getInspectionItemOrder()>0).map(t->t.getInspectionItemOrder().toString()).distinct().collect(Collectors.toList());
                    DocUtils.FileToFileFy(uploadPath + reportTemplateFile,uploadPath + filePath,null,obj.getYjbxxjyxm(),judgConditionMap);
                } else {
                    return Result.error("该产品类型没有找到附页模板");
                }
            }
            report = new BusinessFileInfo();
            report.setInfoName(fileNameDocx);
            report.setInfoVersion(date);
            report.setInfoType("report");
            report.setRemark("");
            report.setOperatorName(StringUtil.getPlatformUsername());
            //report.setInfoType(".docx");
            report.setFileType(".docx");
            report.setDisabled(false);
            report.setFilePath(filePath);
            report.setFileName(fileName);
            report.setFileBeforeName(fileNameDocx);
            report.setFileUrl(uploadPath + filePath);
            businessFileInfoService.insert(report);
            return Result.success("创建附页成功！").addData(uploadPath + filePath);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("system.error");
        }
    }
    @At("/createReport/?")
    @Ok("json")
    @RequiresPermissions("bus.bggl")
    @SLog(tag = "报告生成", msg = "样品id:${args[0]}")
    public Object createReport(String id) {
        try {
            YJbxx obj = yjbxxService.fetchLinks(yjbxxService.fetch(id),"yjbxxjyxm");
            if(obj.getYplx()==null){
                return Result.error("产品类型不能为空，需要根据产品类型适配报告模板！");
            }
            //获取报告模板路径
            BusinessFileInfo reportheaderTemplate = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("infoName", "=", "首页").and("productType","like","%"+obj.getYplx()+"%").and("disabled","=",false));
            if(reportheaderTemplate==null){
                return Result.error("该产品类型未绑定报告首页模板，请联系管理员！");
            }
            String uploadPath = this.getUploadPathConfig();
            String demoheaderReport = uploadPath+reportheaderTemplate.getFilePath();//封面和首页内容模板路径

            //获取生成报告路径
            String date= DateUtil.format(new Date(), "yyyy")+"/"+DateUtil.format(new Date(), "MM")+"/"+DateUtil.format(new Date(), "dd");
            String newReportPath = "/report/" + date + "/" + obj.getId()+".docx";
            String newReport = uploadPath+newReportPath;//生成报告路径
            // 检查之前是否生成过报告，如果生成过则删除
            BusinessFileInfo old_report = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("fileName", "=", obj.getId()));
            if(old_report!=null){
                File old_report_file = new File(uploadPath+old_report.getFilePath());
                old_report_file.delete();
                if (old_report_file.exists()) {
                    if (old_report_file.isFile()) {//boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
                        old_report_file.delete();
                    }
                }
                businessFileInfoService.delete(old_report.getId());
            }
            //获取附页
            BusinessFileInfo fyReport = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("fileName", "=", obj.getId()+"fy"));
            if(fyReport==null){
                return Result.error("请创建附页后再生成报告！");
            }
            String destFyFile = uploadPath+fyReport.getFilePath();//附页路径
            if(StringUtils.isEmpty(obj.getJyrq())||StringUtils.isEmpty(obj.getJyjl())){
                return Result.error("请先【保存信息】！");
            }
            File file = new File(destFyFile);
            if(!file.exists()){
                return Result.error("请先创建附页文档，可以【上传附页】或【复制附页】或【编辑附页】！");
            }


            Map<String, Object> map = new HashMap<String, Object>();
            map.put("P1_ypmc", StringUtils.isEmpty(obj.getYpmc())?"/":obj.getYpmc());
            map.put("P1_bgbh", StringUtils.isEmpty(obj.getBgbh())?"/":obj.getBgbh());
            map.put("P1_bcscdw", StringUtils.isEmpty(obj.getBcscdw())?"/":obj.getBcscdw());
            map.put("P1_sjdw", StringUtils.isEmpty(obj.getSjdw())?"/":obj.getSjdw());
            map.put("P1_wtdw", StringUtils.isEmpty(obj.getWtdw())?"/":obj.getWtdw());
            map.put("P1_jylb", getCodes(obj.getJylx(),"","jylx"));
            map.put("P2_bgbh", StringUtils.isEmpty(obj.getBgbh())?"/":obj.getBgbh());
            map.put("P2_ypmc", StringUtils.isEmpty(obj.getYpmc())?"/":obj.getYpmc());
            map.put("P2_scrqpc", StringUtils.isEmpty(obj.getScrqpc())?"/":obj.getScrqpc());
            map.put("P2_sb", StringUtils.isEmpty(obj.getSb())?"/":obj.getSb());
            map.put("P2_ggxh", StringUtils.isEmpty(obj.getGgxh())?"/":obj.getGgxh());
            map.put("P2_ypdj", StringUtils.isEmpty(obj.getYpdj())?"/":obj.getYpdj());
            map.put("P2_sybh", StringUtils.isEmpty(obj.getSybh())?"/":obj.getSybh());
            map.put("P2_scxkzbh", StringUtils.isEmpty(obj.getScxkzbh())?"/":obj.getScxkzbh());
            map.put("P2_zxbz", StringUtils.isEmpty(obj.getZxbz())?"/":obj.getZxbz());
            map.put("P2_qylxr", StringUtils.isEmpty(obj.getCyry())?"/":obj.getCyry());
            map.put("P2_scrq", StringUtils.isEmpty(obj.getSzcq())?"/":obj.getSzcq());


            map.put("P2_cyjs", StringUtils.isNotEmpty(obj.getCyjs())&&obj.getJylx().equals("jdcc")||obj.getJylx().equals("jbts")||obj.getJylx().equals("zxzz")?obj.getCyjs():"/");
            map.put("P2_ypsl", StringUtils.isEmpty(obj.getJysl())?"/":obj.getJysl()+(StringUtils.isEmpty(obj.getUnit())?"":obj.getUnit()));
            map.put("P2_bysl", StringUtils.isEmpty(obj.getBysl())?"/":obj.getBysl()+(StringUtils.isEmpty(obj.getUnit())?"":obj.getUnit()));
            map.put("P2_ypbh", StringUtils.isEmpty(obj.getYpbh())?"/":obj.getYpbh());
            map.put("P2_ypzt", StringUtils.isEmpty(obj.getYpzt())?"/":obj.getYpzt());
            map.put("P2_packing", StringUtils.isEmpty(obj.getPacking())?"/":obj.getPacking());
            map.put("P2_rwly", StringUtils.isEmpty(obj.getRwly())?"/":obj.getRwly());


            map.put("P2_sydw", StringUtils.isEmpty(obj.getSydw())?"/":obj.getSydw());
            map.put("P2_sydwfr", StringUtils.isEmpty(obj.getSydwlxr())?"/":obj.getSydwlxr());
            map.put("P2_sydwdh", StringUtils.isEmpty(obj.getSydwdh())?"/":obj.getSydwdh());
            map.put("P2_sydwdz", StringUtils.isEmpty(obj.getSydwdz())?"/":obj.getSydwdz());

            map.put("P2_bcscdw", StringUtils.isEmpty(obj.getBcscdw())?"/":obj.getBcscdw());
            map.put("P2_bcscdwfr", StringUtils.isEmpty(obj.getBcscdwlxr())?"/":obj.getBcscdwlxr());
            map.put("P2_bcscdwdh", StringUtils.isEmpty(obj.getBcscdwdh())?"/":obj.getBcscdwdh());
            map.put("P2_bcscdwdz", StringUtils.isEmpty(obj.getBcscdwdz())?"/":obj.getBcscdwdz());

            map.put("P2_scdw", StringUtils.isEmpty(obj.getScdw())?"/":obj.getScdw());
            map.put("P2_scdwfr", StringUtils.isEmpty(obj.getScdwlxr())?"/":obj.getScdwlxr());
            map.put("P2_scdwdh", StringUtils.isEmpty(obj.getScdwdh())?"/":obj.getScdwdh());
            map.put("P2_scdwdz", StringUtils.isEmpty(obj.getScdwdz())?"/":obj.getScdwdz());

            map.put("P2_sjdw", StringUtils.isEmpty(obj.getSjdw())?"/":obj.getSjdw());
            map.put("P2_sjdwfr", StringUtils.isEmpty(obj.getSjdwlxr())?"/":obj.getSjdwlxr());
            map.put("P2_sjdwdh", StringUtils.isEmpty(obj.getSjdwdh())?"/":obj.getSjdwdh());
            map.put("P2_sjdwdz", StringUtils.isEmpty(obj.getSjdwdz())?"/":obj.getSjdwdz());

            map.put("P2_wtdw", StringUtils.isEmpty(obj.getWtdw())?"/":obj.getWtdw());
            map.put("P2_wtdwfr", StringUtils.isEmpty(obj.getWtdwlxr())?"/":obj.getWtdwlxr());
            map.put("P2_wtdwdh", StringUtils.isEmpty(obj.getWtdwdh())?"/":obj.getWtdwdh());
            map.put("P2_wtdwdz", StringUtils.isEmpty(obj.getWtdwdz())?"/":obj.getWtdwdz());

            map.put("P2_ypzt",StringUtils.isEmpty(obj.getYpzt())?"/":obj.getYpzt());
            map.put("P2_jcfyry", StringUtils.isEmpty(obj.getJcfyry())?"/":obj.getJcfyry());
            map.put("P2_jylb", getCodes(obj.getJylx(),"","jylx"));
            map.put("P2_dyrq", StringUtils.isEmpty(obj.getDyrq())?"/":obj.getDyrq().replace("-","/"));
            map.put("P2_jyzq", StringUtils.isEmpty(obj.getLimitDay())?"/":obj.getLimitDay());
            if(!StringUtils.isEmpty(obj.getJyrq())){
               String[] jyrq = obj.getJyrq().split("-");
               if(jyrq.length>1&&jyrq[0].equals(jyrq[1])){
                   map.put("P2_jyrq", jyrq[0]);
               }else{
                   map.put("P2_jyrq", obj.getJyrq());
               }
            }else{
                map.put("P2_jyrq", "/");
            }
            map.put("P2_jyyj", StringUtils.isEmpty(obj.getJyyj())?"/":obj.getJyyj());
            map.put("P2_jyxm", StringUtils.isEmpty(obj.getJyxm())?"/":"共"+convert(obj.getYjbxxjyxm().size())+"项【详见附页】");
            map.put("P2_jyjl", StringUtils.isEmpty(obj.getJyjl())?"/":obj.getJyjl());
            map.put("P2_bz", StringUtils.isEmpty(obj.getBz())?"/":obj.getBz());
            map.put("P2_cydw", StringUtils.isNotEmpty(obj.getCydw())&&obj.getJylx().equals("jdcc")||obj.getJylx().equals("jbts")||obj.getJylx().equals("zxzz")?obj.getCydw():"/");
            map.put("P2_cydd", StringUtils.isNotEmpty(obj.getCydd())&&obj.getJylx().equals("jdcc")||obj.getJylx().equals("jbts")||obj.getJylx().equals("zxzz")?obj.getCydd():"/");
            map.put("P2_cyry", StringUtils.isNotEmpty(obj.getCyryBy())&&obj.getJylx().equals("jdcc")||obj.getJylx().equals("jbts")||obj.getJylx().equals("zxzz")?obj.getCyryBy():"/");
            map.put("P2_cyrq", StringUtils.isNotEmpty(obj.getCyrq())&&obj.getJylx().equals("jdcc")||obj.getJylx().equals("jbts")||obj.getJylx().equals("zxzz")?obj.getCyrq().replace("-","/"):"/");
            //电子签名
            Sys_user slrUser = sysUserService.fetch(StringUtil.getPlatformUid());
            String fileId = slrUser.getFileId();
            if(!StringUtils.isEmpty(fileId)){
                BusinessFileInfo signatureImage = businessFileInfoService.fetch(Cnd.where("id","=",fileId).and("delFlag", "=", "0").and("disabled","=",false));
                if(signatureImage!=null)
                    map.put("P2_zjr", uploadPath+signatureImage.getFilePath());
            }
            if(!StringUtils.isEmpty(obj.getRzfs())){
                List<String> rzfsarray = new ArrayList<>();
                String[] rzfsIds = obj.getRzfs().split(",");
                for (String rzfsid :rzfsIds){
                    BusinessFileInfo rzfsImage = businessFileInfoService.fetch(Cnd.where("id","=",rzfsid).and("delFlag", "=", "0").and("disabled","=",false));
                    if(rzfsImage!=null) {
                        rzfsarray.add(uploadPath + rzfsImage.getFilePath());
                    }
                }
                map.put("P1_rzfs",rzfsarray);
            }

            //生成/获取二维码，只生成一次
            String ewmPath = generateQrCode(obj.getId());
            if(StringUtils.isNotEmpty(ewmPath)){
                map.put("P1_ewm",ewmPath);
            }
            List<String> docs = new ArrayList<String>();
            docs.add(destFyFile);

            //获取尾页,如果有则添加
            BusinessFileInfo reportfootTemplate = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("infoName", "=", "尾页").and("productType","like","%"+obj.getYplx()+"%").and("disabled","=",false));
            if(reportfootTemplate!=null){
                //return Result.error("请上传尾页模板后再生成报告！");
                String demofootReport =uploadPath+reportfootTemplate.getFilePath();//尾页模板
                docs.add(demofootReport);
            }


            map.put("P3_bgbh", obj.getBgbh());//附页
            DocUtils.FileToFile2(demoheaderReport,newReport,map,docs);
//DocUtils.FileToFile2(demoheaderReport,newReport,map,docs);
            BusinessFileInfo report = new BusinessFileInfo();
            report.setInfoName(obj.getId());
            report.setInfoVersion(date);
            report.setInfoType("report");
            report.setRemark("");
            report.setOperatorName(StringUtil.getPlatformUsername());
            report.setFileType(".docx");
            report.setDisabled(false);
            report.setFilePath(newReportPath);
            report.setFileName( obj.getId());
            report.setFileBeforeName( obj.getId()+".docx");
            report.setFileUrl(uploadPath+newReportPath);
            BusinessFileInfo oldReport = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("fileName", "=", obj.getId()));

            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    if(oldReport!=null){
                        businessFileInfoService.delete(oldReport.getId());
                    }
                    businessFileInfoService.insert(report);
                }
            });
            return Result.success("生成成功！").addData(newReport);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("system.error");
        }
    }

    public static String convert(int number) {
        if(number <= 0){
            return "";
        }
        if(number == 1){
            return "壹";
        }
        //数字对应的汉字
        String[] num = {"壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖", ""};
        //单位
        String[] unit = {"", "拾", "佰", "仟", "万", "拾", "佰", "仟", "亿", "拾", "佰", "仟", "万亿"};
        //将输入数字转换为字符串
        String result = String.valueOf(number);
        //将该字符串分割为数组存放
        char[] ch = result.toCharArray();
        //结果 字符串
        String str = "";
        int length = ch.length;
        for (int i = 0; i < length; i++) {
            int c = (int) ch[i] - 48;
            if (c != 0) {
                str += num[c - 1] + unit[length - i - 1];
            }
        }
        if(number < 20 && number > 9){
            str = str.substring(1);
        }
        //System.out.println(str);
        return str ;
    }


    @At("/subReport/?")
    @Ok("json")
    @RequiresPermissions("bus.bggl")
    @SLog(tag = "报告提交", msg = "样品id:${args[0]}")
    public Object subReport(String id,@Param("nextsprIds") String nextsprIds,@Param("nextspr") String nextspr) {
        try {
            YJbxx obj = yjbxxService.fetch(id);

            //获取报告
            BusinessFileInfo report = businessFileInfoService.fetch(Cnd.where("delFlag", "=", "0").and("fileName", "=", obj.getId()));
            if(report==null) {
                return Result.error("请先生成报告！");
            }
            obj.setLczt("5");
            YJbxxLcxx lcxxObj = new YJbxxLcxx();
            lcxxObj.setSpyj("生成报告");
            lcxxObj.setJbxxId(obj.getId());
            lcxxObj.setYpbh(obj.getYpbh());
            lcxxObj.setLczt(obj.getLczt());
            lcxxObj.setNextspr(nextspr);
            lcxxObj.setNextsprIds(nextsprIds);

            Trans.exec(Connection.TRANSACTION_SERIALIZABLE, new Atom() {
                public void run() {
                    yjbxxlcxxservice.execute(Sqls.create("update y_jbxx_lcxx set delflag=1 where lczt>="+obj.getLczt()+" and jbxxid='"+obj.getId()+"'"));
                    yjbxxlcxxservice.insert(lcxxObj);
                    obj.setLczt(obj.getLczt());
                    yjbxxService.update(obj);
                    yjbxxlcxxservice.clearCache();
                }
            });
            return Result.success("提交成功！");
        } catch (Exception e) {
            return Result.error("system.error");
        }
    }

    public String getNames(String ids){
        String names ="";
        if(!StringUtils.isEmpty(ids)){
            String[] id = ids.split(",");
            for(int i = 0 ; i <id.length ;i++){
                names += sysDictService.getNameById(id[i]);
                if(i<(id.length-1)){
                    names+="/";
                }
            }
        }
        return names;
    }

    public String getCodes(String ids,String spl,String parentCode){
        String names ="";
        if(!StringUtils.isEmpty(ids)){
            String[] id = ids.split(",");
            for(int i = 0 ; i <id.length ;i++){
                names += sysDictService.getNameByCode(id[i],parentCode);
                if(i<(id.length-1)){
                    names+=spl;
                }
            }
        }
        return names;
    }
    private String getUploadPathConfig() throws Exception {
        String uploadPath;
        //系统没开启配置,上传到项目路径
        if ("false".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false"))){
            uploadPath= UploadController.class.getClassLoader().getResource("").getPath()+"upload";
        }else if (
                ("true".equals(Globals.MyConfig.getOrDefault("IsConfigUploadPath", "false")))&&(Globals.MyConfig.getOrDefault("ConfigUploadPath", null)!=null)
        ){
            uploadPath=Globals.MyConfig.get("ConfigUploadPath").toString();
        }else {
            throw new Exception("文件上传路径配置有误");
        }
        return uploadPath;
    }

    @At
    @Ok("json")
    @RequiresAuthentication
    public Object downloadWord(@Param("id") String id, HttpServletRequest req) {
        try {
            BusinessFileInfo businessFileInfo = businessFileInfoService.fetch(Cnd.NEW().where("delFlag", "=", false).and("fileName", "=", id+"fy"));
            return Result.success(businessFileInfo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }


    @At
    @Ok("json")
    @RequiresAuthentication
    public Object downloadPdf(@Param("id") String id, HttpServletRequest req) {
        try {
            BusinessFileInfo businessFileInfo = businessFileInfoService.fetch(Cnd.NEW().where("delFlag", "=", false).and("fileName", "=", id+"pdf"));
            return Result.success(businessFileInfo);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error();
        }
    }

    @Aop(TransAop.READ_COMMITTED)
    public String generateQrCode(String id) {
        try {
            String uploadPath= this.getUploadPathConfig();
            String fileName = id+"ewm";
            BusinessFileInfo ewm = businessFileInfoService.fetch(Cnd.NEW().where("delFlag", "=", false).and("fileName", "=", fileName));
            if(ewm!=null){
                return uploadPath+ewm.getFilePath();
            }else{
                String suffixName = "png";
                String fileNameDocx = fileName + "."+suffixName;
                String date = DateUtil.format(new Date(), "yyyy") + "/" + DateUtil.format(new Date(), "MM") + "/" + DateUtil.format(new Date(), "dd");
                String filePath = "/report/" + date + "/" + fileNameDocx;
                // 生成二维码
                QRCodeWriter qrCodeWriter = new QRCodeWriter();
                String path = Globals.AppDomain+"/get-gr-code?qrCodeId="+id;
                BitMatrix bitMatrix = qrCodeWriter.encode(path, BarcodeFormat.QR_CODE, 100, 100);
                BufferedImage qrCodeImage = MatrixToImageWriter.toBufferedImage(bitMatrix);
                // 创建一个 ByteArrayOutputStream
                // 指定输出路径
                File file = new File(uploadPath+filePath);
                if (!file.getParentFile().exists()) {
                    file.getParentFile().mkdirs();
                }
                //ByteArrayOutputStream baos = new ByteArrayOutputStream();
                // 将 BufferedImage 写入 ByteArrayOutputStream
                ImageIO.write(qrCodeImage, suffixName, file);
                //qrCodeUrl = fileApi.createFile("产品二维码"+id, null, baos.toByteArray());
                //baos.close();
                ewm = new BusinessFileInfo();
                ewm.setInfoName(fileNameDocx);
                ewm.setInfoVersion(date);
                ewm.setInfoType("report");
                ewm.setRemark("");
                ewm.setOperatorName(StringUtil.getPlatformUsername());
                //report.setInfoType(".docx");
                ewm.setFileType("."+suffixName);
                ewm.setDisabled(false);
                ewm.setFilePath(filePath);
                ewm.setFileName(fileName);
                ewm.setFileBeforeName(fileNameDocx);
                ewm.setFileUrl(uploadPath + filePath);
                businessFileInfoService.insert(ewm);
                return uploadPath + filePath;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }
}
